package com.pingpang.common.code;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;

public class NettyEncoder extends MessageToByteEncoder<Object> {

    private Class<?> genericClass;
    private MessageCodecUtil messageCodecUtil;

    public NettyEncoder(Class<?> genericClass,MessageCodecUtil messageCodecUtil) {
        this.messageCodecUtil = messageCodecUtil;
        this.genericClass = genericClass;
    }

    @Override
    protected void encode(ChannelHandlerContext channelHandlerContext, Object object, ByteBuf byteBuf) throws Exception {
        if (genericClass.isInstance(object)) {
            byte[] data = messageCodecUtil.encode(object);
            byteBuf.writeInt(data.length);
            byteBuf.writeBytes(data);
        }else {
        	System.out.println("编码类型不符,应为:"+genericClass.getName()+"实际为:"+object.getClass().getName());
        }
    }
}
